<template>
  <view class="product-list">
    <!-- 搜索栏 -->
    <view class="search-bar">
      <view class="search-input-wrapper">
        <image src="/static/image/icon_search.png" class="search-icon" mode="aspectFit"></image>
        <input
          class="search-input"
          v-model="searchKeyword"
          placeholder="搜索商品"
          @confirm="searchProducts"
          @input="onSearchInput"
        />
        <text class="search-btn" :class="{ searching }" @click="searchProducts">
          {{ searching ? '搜索中...' : '搜索' }}
        </text>
      </view>
    </view>

    <!-- 分类筛选 -->
    <!-- 暂时禁用分类功能，因为数据库中没有product_category表 -->

    <view class="category-filter" v-if="categoryList.length > 0">
      <scroll-view class="category-scroll" scroll-x="true">
        <view class="category-list">
          <view
            class="category-item"
            :class="{ active: selectedCategory === null }"
            @click="selectCategory(null)"
          >
            <text class="category-text">全部</text>
          </view>
          <view
            class="category-item"
            v-for="category in categoryList"
            :key="category.id"
            :class="{ active: selectedCategory === category.id }"
            @click="selectCategory(category.id)"
          >
            <text class="category-text">{{ category.name }}</text>
          </view>
        </view>
      </scroll-view>
    </view>


    <!-- 筛选栏 -->
    <!-- <view class="filter-bar">
      <view class="filter-item" :class="{ active: currentSort === 'default' }" @click="sortProducts('default')">
        <text class="filter-text">综合</text>
      </view>
      <view class="filter-item" :class="{ active: currentSort === 'sales' }" @click="sortProducts('sales')">
        <text class="filter-text">销量</text>
      </view>
      <view class="filter-item" :class="{ active: currentSort === 'price' }" @click="sortProducts('price')">
        <text class="filter-text">价格</text>
        <image
          :src="priceSortIcon"
          class="sort-icon"
          mode="aspectFit"
          @click.stop="togglePriceSort"
        ></image>
      </view>
    </view> -->

    <!-- 产品网格 -->
    <scroll-view class="product-grid" scroll-y="true">
      <view class="product-grid-list">
        <view
          class="product-card"
          v-for="product in productList"
          :key="product.id"
          @click="goToDetail(product.id)"
        >
          <view class="product-image-wrapper">
            <image
              :src="product.cover || '/static/image/logo.png'"
              class="product-image"
              mode="aspectFill"
              lazy-load
              @error="onImageError"
            ></image>
            <view class="product-badge" v-if="product.is_hot">
              <text class="badge-text">热销</text>
            </view>
          </view>
          <view class="product-info">
            <text class="product-name">{{ product.name }}</text>
            <view class="product-price-section">
              <text class="product-price">¥{{ getMinPrice(product) }}</text>
              <text class="product-original-price" v-if="getOriginalPrice(product) > getMinPrice(product)">
                ¥{{ getOriginalPrice(product) }}
              </text>
            </view>
            <view class="product-meta">
              <text class="product-sales">已售 {{ product.sales || 0 }}</text>
              <text class="product-stock" v-if="getStockStatus(product)">{{ getStockStatus(product) }}</text>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>
    <!-- 空状态 -->
    <view class="empty-state" v-if="productList.length === 0 && !loading && !loadError">
      <text class="empty-text">暂无商品</text>
      <text class="empty-tip">试试搜索其他商品吧</text>
    </view>
    <!-- <u-tabbar @change="beforeSwitch" active-color="#FFC300" inactive-color="#333" v-model="current" :list="list" icon-size="55" height="120rpx" :mid-button="false"></u-tabbar> -->

  </view>
</template>

<script>
import Navbar from "../../components/Navbar.vue";
import api from "../../config/api.js";

export default {
  components: { Navbar },
  data() {
    return {
      current: 1,
      productList: [],
      categoryList: [],
      selectedCategory: null,
      searchKeyword: '',
      currentSort: 'default', // default, sales, price
      priceSortDirection: 'asc', // asc, desc
      page: 1,
      pageSize: 20,
      hasMore: true,
      loading: false,
      searchTimer: null,
      loadError: false,
      searching: false
    }
  },
  computed: {
    // 价格排序图标
    priceSortIcon() {
      if (this.currentSort !== 'price') {
        return '/static/image/icon_arrow_right.png';
      }
      return this.priceSortDirection === 'asc'
        ? '/static/image/icon_arrow_right.png'
        : '/static/image/icon_arrow_right.png';
    }
  },
  onLoad(options) {
    console.log('产品列表页面加载，参数:', options);

    // 如果有搜索关键词参数
    if (options.keyword) {
      this.searchKeyword = options.keyword;
    }
    // 如果有分类参数
    if (options.category_id) {
      this.selectedCategory = parseInt(options.category_id);
    }
    // 暂时不加载分类数据
    this.loadCategoryList();
    this.loadProductList();
  },
  onPullDownRefresh() {
    this.refreshList();
  },
  onReachBottom() {
    if (this.hasMore && !this.loading) {
      this.loadMore();
    }
  },
  onShow() {
    // 页面显示时，可以刷新购物车数量等数据
    console.log('产品列表页面显示');

    // 重置页面标题
    uni.setNavigationBarTitle({
      title: '特产商城'
    });
  },
  onReady() {
    // 页面渲染完成
    console.log('产品列表页面渲染完成');
  },
  onUnload() {
    // 页面卸载时清理定时器
    if (this.searchTimer) {
      clearTimeout(this.searchTimer);
    }
    console.log('产品列表页面卸载');
  },
  onHide() {
    // 页面隐藏时保存状态
    console.log('产品列表页面隐藏');
  },
  onShareAppMessage() {
    // 页面分享
    return {
      title: '特产商城 - 精选好物',
      path: '/pages/product/product',
      imageUrl: '/static/image/logo.png'
    };
  },
  onShareTimeline() {
    // 分享到朋友圈
    return {
      title: '特产商城 - 精选好物',
      imageUrl: '/static/image/logo.png'
    };
  },
  methods: {
    // 加载分类列表（暂时禁用）
    async loadCategoryList() {
      try {
        const params = {
          status: 1 // 只获取启用的分类
        };
        const result = await api.getProductCategoryList(params);
        this.categoryList = result;
      } catch (error) {
        console.error('加载分类列表失败:', error);
        // 分类功能暂时不可用，不显示错误提示
      }
    },

    // 选择分类（暂时禁用）
    selectCategory(categoryId) {
      this.selectedCategory = categoryId;
      this.refreshList();
    },

    // 加载产品列表
    async loadProductList(isRefresh = false) {
      if (this.loading) return;

      this.loading = true;

      if (isRefresh) {
        this.page = 1;
        this.hasMore = true;
      }

      console.log('加载产品列表:', {
        page: this.page,
        pageSize: this.pageSize,
        searchKeyword: this.searchKeyword,
        currentSort: this.currentSort,
        selectedCategory: this.selectedCategory
      });

      try {
        const params = {
        //   pageNo: this.page,
        //   pageSize: this.pageSize,
		      category_id: this.selectedCategory || '',
          status: 1 // 只获取启用的产品
        };

        // 暂时不添加分类筛选
        // if (this.selectedCategory !== null) {
        //   params.category_id = this.selectedCategory;
        // }

        // 添加搜索关键词
        if (this.searchKeyword.trim()) {
          params.name = this.searchKeyword.trim();
        }

        const result = await api.getProductList(params);

        console.log('API返回结果:', result);

        // 分页API返回的数据结构是 { list: [], total: 0, current: 1, pageSize: 20, totalPages: 1 }
        const data = result || [];

        // 数据验证
        if (!Array.isArray(data)) {
          console.error('API返回的数据格式错误:', data);
          throw new Error('数据格式错误');
        }

        if (isRefresh) {
          this.productList = data;
        } else {
          this.productList = [...this.productList, ...data];
        }

        // 检查是否还有更多数据
        this.hasMore = false
        this.loadError = false;
        this.searching = false;

      } finally {
        this.loading = false;
        uni.stopPullDownRefresh();
      }
    },

    // 刷新列表
    refreshList() {
      this.loadProductList(true);
    },

    // 加载更多
    loadMore() {
      if (this.hasMore && !this.loading) {
        this.page++;
        this.loadProductList();
      }
    },

    // 搜索产品
    searchProducts() {
      this.searching = true;
      this.refreshList();

      // 更新页面标题
      if (this.searchKeyword.trim()) {
        uni.setNavigationBarTitle({
          title: `搜索：${this.searchKeyword}`
        });
      } else {
        uni.setNavigationBarTitle({
          title: '特产商城'
        });
      }
    },

    // 搜索输入处理（防抖）
    onSearchInput() {
      if (this.searchTimer) {
        clearTimeout(this.searchTimer);
      }
      this.searchTimer = setTimeout(() => {
        this.searchProducts();
      }, 800); // 增加防抖时间，减少API调用
    },

    // 排序产品
    sortProducts(sortType) {
      if (this.currentSort === sortType && sortType === 'price') {
        this.togglePriceSort();
        return;
      }

      this.currentSort = sortType;
      if (sortType === 'price') {
        this.priceSortDirection = 'asc';
      }
      this.refreshList();

      // 更新页面标题
      const sortText = {
        'default': '特产商城',
        'sales': '按销量排序',
        'price': '按价格排序'
      };
      uni.setNavigationBarTitle({
        title: sortText[sortType] || '特产商城'
      });
    },

    // 切换价格排序方向
    togglePriceSort() {
      this.priceSortDirection = this.priceSortDirection === 'asc' ? 'desc' : 'asc';
      this.refreshList();

      // 更新页面标题
      const directionText = this.priceSortDirection === 'asc' ? '价格从低到高' : '价格从高到低';
      uni.setNavigationBarTitle({
        title: directionText
      });
    },

    // 获取最低价格
    getMinPrice(product) {
      // 如果产品有SKU，显示最低价格
      if (product.skus && product.skus.length > 0) {
        const minPriceSku = product.skus.reduce((min, sku) =>
          sku.price < min.price ? sku : min
        );
        return minPriceSku.price || 0;
      }
      // 否则显示产品基础价格
      return product.price || 0;
    },

    // 获取原价
    getOriginalPrice(product) {
      // 如果产品有SKU，显示最高原价
      if (product.skus && product.skus.length > 0) {
        const maxOriginalPriceSku = product.skus.reduce((max, sku) =>
          (sku.original_price || 0) > (max.original_price || 0) ? sku : max
        );
        return maxOriginalPriceSku.original_price || 0;
      }
      // 否则显示产品原价
      return product.original_price || product.price || 0;
    },

    // 获取库存状态
    getStockStatus(product) {
      // 如果产品有SKU，计算总库存
      if (product.skus && product.skus.length > 0) {
        const totalStock = product.skus.reduce((sum, sku) => sum + (sku.stock || 0), 0);
        if (totalStock <= 0) {
          return '无货';
        } else if (totalStock < 10) {
          return '库存紧张';
        }
      } else {
        // 否则使用产品基础库存
        if (product.stock !== undefined) {
          if (product.stock <= 0) {
            return '无货';
          } else if (product.stock < 10) {
            return '库存紧张';
          }
        }
      }
      return '';
    },

    // 图片加载错误处理
    onImageError(e) {
      // 可以在这里设置默认图片
      console.log('图片加载失败:', e);
    },

    // 跳转到产品详情
    goToDetail(productId) {
      console.log('跳转到产品详情:', productId);
      uni.navigateTo({
        url: `/pages/product/detail?id=${productId}`
      });
    }
  }
}
</script>

<style lang="scss">
.product-list {
  height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;

  // 搜索栏
  .search-bar {
    background: #FFFFFF;
    padding: 24rpx 32rpx;
    border-bottom: 1rpx solid #f0f0f0;

    .search-input-wrapper {
      display: flex;
      align-items: center;
      background: #f8f8f8;
      border-radius: 24rpx;
      padding: 16rpx 24rpx;

      .search-icon {
        width: 32rpx;
        height: 32rpx;
        margin-right: 16rpx;
      }

      .search-input {
        flex: 1;
        font-size: 28rpx;
        color: #333333;
      }

      .search-btn {
        font-size: 28rpx;
        color: #333;
        padding-left: 16rpx;

        &.searching {
          color: #999999;
        }
      }
    }
  }

  // 分类筛选
  .category-filter {
    background: #FFFFFF;
    border-bottom: 1rpx solid #f0f0f0;

    .category-scroll {
      white-space: nowrap;
    }

    .category-list {
      display: flex;
      padding: 24rpx 32rpx;
      gap: 24rpx;

      .category-item {
        flex-shrink: 0;
        padding: 12rpx 24rpx;
        background: #f8f8f8;
        border-radius: 12rpx;
        &.active {
          background: #FFC300;
          .category-text {
            color: #333;
          }
        }

        .category-text {
          font-size: 26rpx;
          color: #666666;
        }
      }
    }
  }

  // 筛选栏
  .filter-bar {
    background: #FFFFFF;
    display: flex;
    padding: 24rpx 32rpx;
    border-bottom: 1rpx solid #f0f0f0;

    .filter-item {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 16rpx 0;

      &.active {
        .filter-text {
          color: #FFC300;
        }
      }

      .filter-text {
        font-size: 28rpx;
        color: #666666;
      }

      .sort-icon {
        width: 24rpx;
        height: 24rpx;
        margin-left: 8rpx;
        transform: rotate(90deg);
      }
    }
  }
  .product-grid {
    flex-grow: 1;
    overflow: hidden;
  }
  // 产品网格
  .product-grid-list {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 24rpx;
    padding: 24rpx;

    .product-card {
      background: #FFFFFF;
      border-radius: 16rpx;
      overflow: hidden;
      transition: all 0.3s ease;
      cursor: pointer;
      .product-image-wrapper {
        position: relative;
        width: 100%;
        height: 320rpx;
        background: #f8f8f8;
        border-radius: 16rpx 16rpx 0 0;
        overflow: hidden;

        .product-image {
          width: 100%;
          height: 100%;
        }

        .product-badge {
          position: absolute;
          top: 16rpx;
          left: 16rpx;
          background: #ff4d4f;
          border-radius: 12rpx;
          padding: 8rpx 12rpx;

          .badge-text {
            font-size: 20rpx;
            color: #FFFFFF;
          }
        }
      }

      .product-info {
        padding: 24rpx;

        .product-name {
          font-size: 28rpx;
          color: #333333;
          line-height: 1.4;
          margin-bottom: 8rpx;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 2;
          overflow: hidden;
          word-break: break-all;
        }

        .product-price-section {
          display: flex;
          align-items: center;
          margin-bottom: 8rpx;

          .product-price {
            font-size: 32rpx;
            color: #ff4d4f;
            font-weight: bold;
            margin-right: 12rpx;
          }

          .product-original-price {
            font-size: 24rpx;
            color: #999999;
            text-decoration: line-through;
          }
        }

        .product-meta {
          display: flex;
          justify-content: space-between;
          align-items: center;

          .product-sales {
            font-size: 24rpx;
            color: #666666;
          }

          .product-stock {
            font-size: 24rpx;
            color: #ff4d4f;
          }
        }
      }
    }
  }

  // 加载更多
  .load-more {
    text-align: center;
    padding: 32rpx;

    .load-more-text {
      font-size: 28rpx;
      color: #FFC300;
    }
  }

  // 空状态
  .empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 120rpx 32rpx;

    .empty-image {
      width: 200rpx;
      height: 200rpx;
      margin-bottom: 32rpx;
    }

    .empty-text {
      font-size: 28rpx;
      color: #999999;
      margin-bottom: 8rpx;
    }

    .empty-tip {
      font-size: 24rpx;
      color: #cccccc;
    }
  }

  // 错误状态
  .error-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 120rpx 32rpx;

    .error-image {
      width: 200rpx;
      height: 200rpx;
      margin-bottom: 32rpx;
    }

    .error-text {
      font-size: 28rpx;
      color: #ff4d4f;
      margin-bottom: 8rpx;
    }

    .error-tip {
      font-size: 24rpx;
      color: #999999;
      margin-bottom: 32rpx;
    }

    .retry-btn {
      background: #FFC300;
      color: #FFFFFF;
      border: none;
      border-radius: 24rpx;
      padding: 16rpx 32rpx;
      font-size: 28rpx;
    }
  }

  // 加载状态
  .loading-state {
    text-align: center;
    padding: 32rpx;

    .loading-spinner {
      width: 60rpx;
      height: 60rpx;
      border: 4rpx solid #f3f3f3;
      border-top: 4rpx solid #FFC300;
      border-radius: 50%;
      animation: spin 1s linear infinite;
      margin: 0 auto 16rpx;
    }

    .loading-text {
      font-size: 28rpx;
      color: #666666;
    }
  }

  @keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
  }

  // 底部加载状态
  .bottom-loading {
    text-align: center;
    padding: 24rpx;

    .loading-text {
      font-size: 26rpx;
      color: #999999;
    }
  }
}
</style>
